﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using XbsWebAPI.EntityFrameworkCore;
using XbsWebAPI.EntityFrameworkCore.Entities;

namespace XbsWebAPI.Core.Repositories
{
    public class MiniProgramRepository : IMiniProgramRepository
    {
        private readonly DataContext _dbContext;

        public MiniProgramRepository(DataContext dataContext)
        {
            _dbContext = dataContext;
        }


        public IQueryable<MiniProgram> AsQueryable()
        {
           return _dbContext.MiniPrograms.AsQueryable();
           
        }
        //更新数据库
        public MiniProgram Create(MiniProgram entity)
        {
            entity.Id = Guid.NewGuid();
            entity.CreationDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            _dbContext.Add(entity);
            _dbContext.SaveChanges();

            return entity;
        }
        public Task<MiniProgram> CreateAsync(MiniProgram entity)
        {
            return Task.FromResult(Create(entity));
        }

        public MiniProgram Delete(Guid id)
        {
            var model = _dbContext.MiniPrograms.FirstOrDefault(x => x.Id == id);
            if (model == null)
                return null;
            _dbContext.Remove(model);
            _dbContext.SaveChanges();

            return model;
        }

        public Task<MiniProgram> DeleteAsync(Guid id)
        {
            return Task.FromResult(Delete(id));
        }

        public IQueryable<MiniProgram> Query(Expression<Func<MiniProgram, bool>> filter)
        {
            var query = _dbContext.MiniPrograms.Where(filter);

            return query;
        }

        public MiniProgram QueryById(Guid id)
        {
            return _dbContext.MiniPrograms.FirstOrDefault(x => x.Id == id);
        }

        public MiniProgram Update(MiniProgram entity)
        {
            var model = _dbContext.MiniPrograms.AsNoTracking().FirstOrDefault(x => x.Id == entity.Id);
            if (model == null)
                return null;

            entity.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            entity.CreationDate = model.CreationDate;
            _dbContext.MiniPrograms.Update(entity);
            _dbContext.SaveChanges();

            return entity;
        }

        public Task<MiniProgram> UpdateAsync(MiniProgram entity)
        {
            return Task.FromResult(Update(entity));
        }


    }
}
